import React, { useCallback, useState, useEffect } from "react";
import TweenOne from "rc-tween-one";
import OverPack from "rc-scroll-anim/lib/ScrollOverPack";
import { register, sendCode } from "@/api/Api";
import {
  Button,
  Form,
  Input,
  Checkbox,
  message,
  Tooltip,
  Row,
  Col,
} from "antd";
import LazyLoad from "react-lazyload";
import getConfig from "next/config";
import { ReactSVG } from "react-svg";

const { publicRuntimeConfig } = getConfig();
const Footer = ({ isMobile, ...props }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const submitRegister = useCallback(async (sendData) => {
    try {
      setLoading(true);
      const res = await register(sendData);
      setLoading(false);
      if (res && res.ok) {
        message.success(res.data || "注册成功，请等待审批");
      } else {
        message.error(`${res.message || "注册失败"}`);
      }
    } catch (e) {
      setLoading(false);
    }
  }, []);

  const { dataSource } = props;
  delete props.dataSource;

  const onFinish = (values) => {
    submitRegister(values);
  };

  const onFinishFailed = (values) => {};

  const [time, setTime] = useState(59); // timer

  // 短信验证
  const verifiedSubmit = () => {
    const { getFieldValue } = form;
    const phone = getFieldValue("phone");
    if (new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/, "g").test(phone)) {
      loadTencentCaptcha();
    } else {
      message.error("请输入正确的手机号码");
    }
  };

  const goUp = () => {
    const anchorName = "Nav0_0";
    // 找到锚点
    let anchorElement = document.getElementById(anchorName);
    // 如果对应id的锚点存在，就跳转到锚点
    if (anchorElement) {
      anchorElement.scrollIntoView({ block: "start", behavior: "smooth" });
    }
  };

  const callback = (res) => {
    /* res（验证成功） = {ret: 0, ticket: "String", randstr: "String"}
       res（客户端出现异常错误 仍返回可用票据） = {ret: 0, ticket: "String", randstr: "String", errorCode: Number, errorMessage: "String"}
       res（用户主动关闭验证码）= {ret: 2}
    */
    if (res.ret === 0 && !res.errorCode) {
      setLoading(true);
      submitPhonrVerify(res);
    }
  };

  const submitPhonrVerify = async ({ ticket, randstr }) => {
    const { getFieldValue } = form;
    const phone = getFieldValue("phone");
    const res = await sendCode({
      phone: (phone || "").trim(),
      ticket,
      randStr: randstr,
    });
    if (res && res.ok) {
      message.success("短信验证码已发送，注意查看手机");
    }
  };

  // 验证码js加载错误处理
  const loadErrorCallback = () => {
    const CaptchaAppId = "2056026228";
    /* 生成票据或自行做其它处理 */
    const ticket = `terror_1001_${CaptchaAppId}${Math.floor(
      new Date().getTime() / 1000
    )}`;
    callback({
      ret: 0,
      randstr: `@${Math.random().toString(36).substr(2)}`,
      ticket,
      errorCode: 1001,
      errorMessage: "jsload_error",
    });
  };

  const loadTencentCaptcha = () => {
    const CaptchaAppId = "2056026228";
    try {
      const captcha = new TencentCaptcha(CaptchaAppId, callback);
      // captcha.langFun();
      // 滑块显示
      captcha.show();
    } catch (error) {
      loadErrorCallback();
    }
  };

  useEffect(() => {
    let timer = setInterval(() => {
      if (time > 0 && loading) {
        setTime(time - 1);
      } else {
        setTime(59);
        setLoading(false);
      }
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, [time, loading]);

  return (
    <div {...props} {...dataSource.wrapper}>
      <OverPack>
        <TweenOne
          animation={{ y: "+=0", opacity: 1, type: "from" }}
          key="footer"
        >
          <div className="footer-bg">
            <a name="register"></a>
          </div>
          <div className="footer-detail">
            <div className="contact-form">
              <div className="contact-form-flex">
                <Form
                  form={form}
                  name="basic"
                  layout="vertical"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  autoComplete="off"
                  labelAlign="left"
                  requiredMark={false}
                >
                  <div className="left">
                    <Form.Item
                      className="item"
                      label={
                        <a
                          style={{ cursor: "auto", color: "white" }}
                          //name="register"
                        >
                          姓名
                        </a>
                      }
                      name="name"
                      rules={[
                        {
                          required: true,
                          message: "不能为空",
                        },
                        {
                          max: 50,
                          message: "长度不能超过50",
                        },
                      ]}
                    >
                      <Input placeholder="请输入手机号/用户名" />
                    </Form.Item>
                    <Form.Item
                      className="item"
                      label="手机号码"
                      name="phone"
                      rules={[
                        {
                          required: true,
                          message: "手机号码不能为空",
                        },
                        {
                          pattern: new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/, "g"),
                          message: "请输入正确手机号码",
                        },
                      ]}
                    >
                      <Input placeholder="请输入手机号码" />
                    </Form.Item>
                    <Form.Item
                      className="item"
                      label="验证码"
                      name="code"
                      validateTrigger="onBlur"
                      rules={[
                        {
                          required: true,
                          message: "验证码不能为空",
                        },
                        {
                          len: 6,
                          message: "验证码长度为6",
                        },
                      ]}
                    >
                      <div className="form-box flex">
                        <div>
                          <Input placeholder="请输入验证码" />
                        </div>

                        <Button
                          disabled={loading}
                          type="primary"
                          className="code"
                          loading={loading}
                          onClick={verifiedSubmit}
                        >
                          {loading ? `${time}秒` : "获取短信验证码"}
                        </Button>
                      </div>
                    </Form.Item>
                    <Form.Item
                      className="item"
                      label="邮箱地址"
                      name="email"
                      rules={[
                        {
                          required: true,
                          message: "邮箱地址不能为空",
                        },
                        {
                          type: "email",
                          message: "这不是一个合法的邮箱",
                        },
                      ]}
                    >
                      <Input placeholder="请输入邮箱地址" />
                    </Form.Item>
                    <Form.Item
                      style={{ borderBottom: "1px solid #bdbdbd" }}
                      className="item"
                      label="公司名称"
                      name="company"
                      rules={[
                        {
                          required: true,
                          message: "公司名称不能为空",
                        },
                        {
                          max: 50,
                          message: "长度不能超过50",
                        },
                      ]}
                    >
                      <Input placeholder="请输入公司名称" />
                    </Form.Item>
                    <Form.Item
                      style={{ left: "200px" }}
                      name="agreement"
                      valuePropName="checked"
                      rules={[
                        {
                          validator: (_, value) =>
                            value
                              ? Promise.resolve()
                              : Promise.reject(new Error("请勾选协议")),
                        },
                      ]}
                    >
                      <Checkbox style={{ color: "#FFFFFF" }}>
                        我已阅读并同意{" "}
                        <a
                          className="login-form-forgot"
                          href={`${publicRuntimeConfig.basePath}/userservice`}
                          target="_blank"
                        >
                          《用户协议》
                        </a>
                        <a
                          className="login-form-forgot"
                          href={`${publicRuntimeConfig.basePath}/privacypolicy`}
                          target="_blank"
                        >
                          《隐私声明》
                        </a>
                      </Checkbox>
                    </Form.Item>
                  </div>
                  <div className="right">
                    <div className="title">
                      <div>
                        <p className="top">CONTACT</p>
                        <p className="bottom">申请试用，请留下您的联系方式</p>
                      </div>
                    </div>
                    <div className="subtitle">
                      <p>云原生实时数据湖客户经理将尽快与您联系</p>
                    </div>
                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                      <Button type="primary" htmlType="submit">
                        提交
                      </Button>
                    </Form.Item>
                  </div>
                </Form>
              </div>
            </div>
            <div
              animation={{ y: "+=30", opacity: 0, type: "from" }}
              key="footer1"
              className="box"
            >
              <Row>
                {dataSource.detail.children.map((i, key) => (
                  <Col xs={24} md={8} key={key}>
                    <div className="item">
                      <div>
                        <div className="title_content">
                          <div>
                            <ReactSVG className="svg-icon" src={i.icon} />
                            <div className="bottom-line"></div>
                          </div>
                          <p className="title">{i.title}</p>
                        </div>
                        {i.subtitle.map((k, _key) => {
                          return (
                            <p key={_key} className="subtitle">
                              {k.href ? (
                                <a key={_key} href={k.href} target="_blank">
                                  {k.text}
                                </a>
                              ) : (
                                <span>{k}</span>
                              )}
                            </p>
                          );
                        })}
                      </div>
                    </div>
                  </Col>
                ))}
              </Row>
            </div>
            {!isMobile && (
              <Tooltip placement="top" title="回到顶部">
                <span className="goUp" onClick={goUp}></span>
              </Tooltip>
            )}
          </div>
          <div className="footer-copyright">
            {/* —————————&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; */}
            {dataSource.copyright.children}
            {/* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;————————— */}
          </div>
        </TweenOne>
      </OverPack>
    </div>
  );
};

export default Footer;
